package cn.edu.zut.sunday.utils;

import com.google.common.collect.Lists;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

@Slf4j
@UtilityClass
public class ReloadFileUtils {

    public static List<File> getFiles(String path) throws Exception {
        final Path pathVal = Paths.get(ResourceUtils.getFile("classpath:").getPath(), path);
        log.info("files path: {}", pathVal);
        File       file  = pathVal.toFile();
        List<File> files = new ArrayList<>();
        if (file.isFile()) {
            return Lists.newArrayList(file);
        }

        files = Lists.newArrayList(file.listFiles());
        return files;
    }

    public static boolean isDirectory(String path) throws Exception {
        final URL resource = ReloadFileUtils.class.getClassLoader().getResource(path);
        if (resource == null) {
            throw new Exception("读取文件:[ " + path + " ]失败!");
        }
        final File file = new File(resource.toURI());
        return file.isDirectory();
    }


    public static List<String> readFiles(File file) {
        List<File> list = null;
        if (file.isFile()) {
            list = Lists.newArrayList(file);
        } else {
            list = Arrays.asList(Objects.requireNonNull(file.listFiles()));
        }

        return list.stream().map(f -> {
            try {
                return readFile(f);
            } catch (IOException e) {
                log.error("read file: {} failed!", f.getName());
            }
            return "";
        }).collect(Collectors.toList());
    }

    public static String readFile(File file) throws IOException {
        try (final BufferedReader bufferedReader =
          Files.newBufferedReader(Paths.get(file.toURI()),
            StandardCharsets.UTF_8)) {
            return bufferedReader.toString();
        }
    }

    public static List<String> readFileAllLines(File file) throws IOException {
        return Files.readAllLines(Paths.get(file.toURI()),
          StandardCharsets.UTF_8);

    }

    public static long lines(File file) {
        try {
            return Files.readAllLines(Paths.get(file.toURI()),
              StandardCharsets.UTF_8).size();
        } catch (IOException e) {
            log.info("get the number of lines error: {}", file.getName());
        }
        return 0;
    }
}
